import CommonAction from './common';

import { toast, cacheTools, promptBox, base } from 'nc-lightapp-front';

let { NCDatePicker } = base;

import { formatDate } from '../../../../hrpub/common/utils/utils';

export default class table extends CommonAction {
	constructor(comp) {
		super();
		this.comp = comp;
	}

	didMount = () => {};

	initData = ({ queryCondition, billStatus, time, beginTime, endTime, pk_org, pageInfo, probationType } = {}) => {
		const { props } = this.comp;
		const { dispatch, editTable, exam, cardPagination, meta } = props;
		const { createCardPagination } = cardPagination;

		let template = meta.getMeta();
		let oid = template['query'].oid;
		// 如果没有传入参数的话就从store中获取
		!queryCondition && (queryCondition = exam.queryCondition);
		!billStatus && (billStatus = exam.billStatus);
		!time && (time = exam.time);
		!pageInfo && (pageInfo = exam.pageInfo);
		!beginTime && (beginTime = exam.beginTime);
		!endTime && (endTime = exam.endTime);
		!pk_org && (pk_org = exam.refValue ? exam.refValue.refpk : '');
		!probationType && (probationType = exam.probationType);
		probationType === '3' && (probationType = '');

		let postData = {
			...queryCondition,
			pageInfo: {
				...pageInfo,
				pageIndex: pageInfo.pageIndex
			},
			billStatus,
			time,
			beginTime,
			endTime,
			pk_org,
			probationType,
			oid,
			queryAreaCode: 'search'
		};

		postData.billTime === 'custom' && (postData.billTime = '');

		postData.pageInfo.pageIndex = postData.pageInfo.pageIndex.toString();

		postData.pageInfo.pageSize = postData.pageInfo.pageSize.toString();

		dispatch({
			type: 'exam/getMainTableData',
			payload: {
				postData: postData
			}
		}).then((res) => {
			if (res.success) {
				if (res.data && res.data.list) {
					let pageInfo = this.deepCopy(res.data.list.pageInfo);
					dispatch({
						type: 'exam/update',
						payload: {
							pageInfo: {
								...pageInfo,
								pageIndex: parseInt(pageInfo.pageIndex)
							},
							allpks: res.data.list.allpks
						}
					});
					cacheTools.set('allpks', res.data.list.allpks);
					editTable.setTableData('list', res.data.list, false);
					editTable.showColByKey('list', 'opr')
				} else {
					dispatch({
						type: 'exam/update',
						payload: {
							allpks: []
						}
					});
					cacheTools.set('allpks', []);
					editTable.setTableData('list', { rows: [] }, false);
				}
			} else {
				dispatch({
					type: 'exam/update',
					payload: {
						allpks: []
					}
				});
				cacheTools.set('allpks', []);
				editTable.setTableData('list', { rows: [] }, false);
			}
		});
	};
	getWidgetTableData = ({value, pageInfo } = {}) => {
		const { props } = this.comp;
		const { dispatch, editTable, exam, cardPagination, meta } = props;
		// let template = meta.getMeta();
		!pageInfo && (pageInfo = exam.pageInfo);

		let postData = {
			widgetCode:"6008C060",
			appCode:"60092040",
			pageCode:"60092040nccloud",
			areaCode:"list",
			pageInfo: {
				pageSize: parseInt(pageInfo.pageSize),
				total: parseInt(pageInfo.total),
				totalPage:parseInt(pageInfo.totalPage),
				pageIndex:  parseInt(pageInfo.pageIndex),
			},
		};
		dispatch({
			type: 'exam/getWidgetTableData',
			payload: {
				postData: postData
			}
		}).then((res) => {
			if (res.success) {
				if (res.data && res.data.list) {
					let pageInfo = this.deepCopy(res.data.list.pageInfo);
					dispatch({
						type: 'exam/update',
						payload: {
							pageInfo: {
								...pageInfo,
								pageIndex: parseInt(pageInfo.pageIndex)
							},
							allpks: res.data.list.allpks
						}
					});
					cacheTools.set('allpks', res.data.list.allpks);
					editTable.setTableData('list', res.data.list, false);
					editTable.hideColByKey('list', 'opr')
				} else {
					dispatch({
						type: 'exam/update',
						payload: {
							allpks: []
						}
					});
					cacheTools.set('allpks', []);
					editTable.setTableData('list', { rows: [] }, false);
				}
			} else {
				dispatch({
					type: 'exam/update',
					payload: {
						allpks: []
					}
				});
				cacheTools.set('allpks', []);
				editTable.setTableData('list', { rows: [] }, false);
			}
		});
	};
	doubleClickTool = (data) => {
		const { props, action } = this.comp;
		const { dispatch, exam, form } = props;
		dispatch({
			type: 'exam/update',
			payload: {
				cardMode: true,
				editState: false,
				billid: data.values.pk_hi_regapply.value
			}
		});
		action.formAct.oneAction(data.values.pk_hi_regapply.value);
	};

	// 表格双击行事件

	doubleClick = (data, index) => {
		const { props, action } = this.comp;
		const { dispatch, exam, form } = props;
		if (index === false) {
			// 解决单击跳转与双击跳转是否为函数体的问题
			return () => {
				this.doubleClickTool(data);
			};
		} else {
			this.doubleClickTool(data);
		}

		// this.editFunc(data,index)
	};

	// 修改表格行数据
	editTableRow = (data, index) => {
		return () => {
			this.editFunc(data, index);
		};
	};

	// 修改表格公用方法
	editFunc = (data, index) => {
		const { props, action } = this.comp;
		const { dispatch, exam, form, meta } = props;
		let postData = {
			area_code: 'card',
			billid: data ? data.values.pk_hi_regapply.value : exam.billid,
			page_code: exam.config.pagecode,
			isapprove: exam.fromApprove === true ? true : false,
			pk_org: exam.refValue.refpk
		};

		dispatch({
			type: 'exam/regApplyEditAction',
			payload: {
				postData: postData
			}
		}).then((res) => {
			if (res.success) {
				if (res.data && res.data.formData) {
					form.EmptyAllFormValue('card');
					this.functionStateTool(res.data);

					// 开启卡片模式
					dispatch({
						type: 'exam/update',
						payload: {
							cardMode: true,
							editState: true,
							page: '',
							type: res.data.formData.card.rows[0].values.probation_type.value
						}
					});
					action.btnAct.buttonTool(props, false);
					// 展开子列表
					form.openArea('card', 'psninfo');
					form.openArea('card', 'oldinfo');
					form.openArea('card', 'newinfo');
					form.openArea('card', 'execinfo');
					form.openArea('card', 'audit_info');
					form.openArea('card', 'table_end_info');

					form.setFormStatus('card', 'edit');

					form.setAllFormValue({ card: res.data.formData.card });
				} else {
					dispatch({
						type: 'exam/update',
						payload: {
							editState: false,
							page: ''
						}
					});
					toast({ color: 'warning', content: res.data.message });
				}
			}
		});
	};

	// 卡片页面功能禁用隐藏公共方法、修改、复制、新增、单条查看
	functionStateTool = (data) => {
		const { props } = this.comp;
		const { form } = props;

		let newobj = {}; //转正后隐藏集
		let oldobj = {}; //转正前隐藏集
		let psninfo = {}; //工作信息禁用集
		let card = {}; //主表禁用集
		let newobjDisabled = {}; //转正后禁用集
		let oldobjDisabled = {};
		// 设置转正前后信息的显示隐藏
		let required = {};
		data.newinfo.items.forEach((item) => {
			newobj[item.attrcode] = item.visible;
			required[item.attrcode] = item.required;
			newobjDisabled[item.attrcode] = item.disabled;
		});
		data.oldinfo.items.forEach((item) => {
			oldobj[item.attrcode] = item.visible;
			required[item.attrcode] = item.required;
			oldobjDisabled[item.attrcode] = item.disabled;
		});

		form.setFormItemsVisible('card', {
			...newobj,
			...oldobj
		});

		data.psninfo.items.forEach((item) => {
			psninfo[item.attrcode] = item.disabled;
			required[item.attrcode] = item.required;
		});
		data.card.items.forEach((item) => {
			card[item.attrcode] = item.disabled;
			required[item.attrcode] = item.required;
		});
		form.setFormItemsDisabled('card', {
			...newobjDisabled,
			...oldobjDisabled,
			...psninfo,
			...card
		});

		form.setFormItemsRequired('card', required);
	};

	// 复制行数据
	copyTableRow = (data, index) => {
		const { props, action } = this.comp;
		const { dispatch, exam, form } = props;
		return () => {
			let postData = {
				area_code: 'card',
				billid: data.values.pk_hi_regapply.value,
				page_code: exam.config.pagecode,
				pk_org: exam.refValue.refpk
			};
			dispatch({
				type: 'exam/regApplyCopyAction',
				payload: {
					postData: postData
				}
			}).then((res) => {
				if (res.success) {
					if (res.data && res.data.form) {
						dispatch({
							type: 'exam/update',
							payload: {
								cardMode: true,
								editState: true,
								page: 'add',
								type: res.data.form.card.rows[0].values.probation_type.value
							}
						});

						this.functionStateTool(res.data);

						if (res.data.isBillCodeEditable === true) {
							form.setFormItemsDisabled('card', { bill_code: false });
						} else {
							form.setFormItemsDisabled('card', { bill_code: true });
						}
						action.btnAct.buttonTool(props, false);
						// 展开子列表
						form.openArea('card', 'psninfo');
						form.openArea('card', 'oldinfo');
						form.openArea('card', 'newinfo');
						form.openArea('card', 'execinfo');
						form.openArea('card', 'audit_info');
						form.openArea('card', 'table_end_info');

						form.setFormStatus('card', 'edit');
						form.setAllFormValue({ card: res.data.form.card });
					} else {
						toast({ color: 'warning', content: res.data.message });
					}
				} else {
					// editTable.setTableData('list', {rows: []}, false);
				}
			});
		};
	};

	// 批量删除
	batchDelete = (billid) => {
		const { props, action } = this.comp;
		const { dispatch, exam, editTable } = props;

		if (exam.cardMode === false) {
			let arr = this.billidTool();
			if (arr && arr.length > 0) {
				this.promptBoxTool(billid);
			}
		} else {
			this.promptBoxTool(billid);
		}
	};

	promptBoxTool = (billid) => {
		const { props } = this.comp;
		const { exam } = props;
		promptBox({
			color: 'warning',
			title: exam.json['gx6008-000019'], //您确定要删除吗?
			noCancelBtn: false,
			beSureBtnName: exam.json['gx6008-000024'], //确定
			cancelBtnName: exam.json['gx6008-000025'], //取消
			hasCloseBtn: false,
			beSureBtnClick: this.functionSure.bind(this, billid)
		});
	};

	functionSure = (billid) => {
		const { props } = this.comp;
		const { exam } = props;
		if (exam.cardMode === true) {
			this.cardDelete(billid);
		} else {
			this.tableDelete(billid);
		}
	};

	// 卡片单个删除
	cardDelete = async (billid) => {
		const { props, action } = this.comp;
		const { dispatch, exam, editTable, cardPagination } = props;
		if (!billid) {
			return;
		}
		// let nextId = cardPagination.getNextCardPaginationId({id:billid,status:1})
		let arr = cacheTools.get('allpks');
		let ind = cacheTools.get('allpks').indexOf(billid) + 1;
		let nextId = arr[ind];
		if (!nextId) {
			nextId = arr[ind - 2];
		}
		// return
		let postData = {
			billids: billid,
			pk_org: exam.refValue.refpk
		};
		try {
			let res = await dispatch({
				type: 'exam/deleteBatch',
				payload: {
					postData: postData
				}
			});
			if (res.success) {
				if (res.data.errorMsg) {
					//错误信息存在
					toast({ color: 'warning', content: res.data.errorMsg });
				} else {
					var allpks = exam.allpks;
					var inx = allpks.indexOf(billid);
					allpks.splice(inx, 1);
					cacheTools.set('allpks', allpks);

					// cardPagination.setCardPaginationId({id:billid,status:3})
					cardPagination.setCardPaginationId({ id: nextId, status: 1 });

					dispatch({
						type: 'exam/update',
						payload: {
							allpks: allpks
						}
					});
					// 如果缓存allpks为空，则删除后直接返回table页面

					if (cacheTools.get('allpks').length <= 0) {
						action.formAct.goToBackMainPage();
					} else {
						// 渲染下一条数据
						action.formAct.oneAction(nextId);
					}
					// 删除成功！
					toast({ color: 'success', content: exam.json['gx6008-000017'] });
				}
			}
		} catch (e) {}
	};

	// 获取表格多选单据id公共方法
	billidTool = () => {
		const { props, action } = this.comp;
		const { dispatch, exam, editTable } = props;
		let data = editTable.getCheckedRows('list');
		if (data.length === 0 && exam.cardMode === false) {
			toast({
				color: 'warning',
				content: exam.json['gx6008-000016']
			});
			return;
		}
		let arr = [];
		data.forEach((item) => {
			arr.push(item.data.values.pk_hi_regapply.value);
		});
		return arr;
	};

	// 表格批量删除
	tableDelete = async () => {
		const { props, action } = this.comp;
		const { dispatch, exam, editTable } = props;

		let arr = this.billidTool();

		if (!arr || arr.length <= 0) {
			return;
		}
		let postData = {
			billids: arr,
			pk_org: exam.refValue.refpk
		};
		try {
			let res = await dispatch({
				type: 'exam/deleteBatch',
				payload: {
					postData: postData
				}
			});
			if (res.success) {
				if (res.data.errorMsg) {
					toast({ color: 'warning', content: res.data.errorMsg });
				} else {
					toast({ color: 'success', content: exam.json['gx6008-000017'] });
					this.pubSub.publish('initData');
				}
			}
		} catch (e) {}
	};

	// 附件管理存储billid
	enclosure = (data, index) => {
		const { props, action } = this.comp;
		const { dispatch, exam, form } = props;
		return () => {
			dispatch({
				type: 'exam/update',
				payload: {
					billid: data.values.pk_hi_regapply.value,
					fileManagerModalVisible: true
				}
			});
		};
	};

	// 提交单据

	batchCommit = async (value) => {
		const { props, action } = this.comp;
		const { dispatch, exam, form } = props;

		try {
			let arr = this.billidTool();
			if (arr.length <= 0 && exam.cardMode === false) {
				return;
			}
			let postData = {
				billids: exam.cardMode === true ? exam.billid : arr,
				pk_org: exam.refValue.refpk
			};
			if (value) {
				postData = Object.assign(
					{},
					{
						billids: exam.cardMode === true ? exam.billid : arr,
						pk_org: exam.refValue.refpk
					},
					{ content: value }
				);
			}

			let res = await dispatch({
				type: 'exam/batchCommit',
				payload: {
					postData: postData
				}
			});
			if (res.success) {
				// 提交成功
				if (res.data.content) {
					dispatch({
						type: 'exam/update',
						payload: {
							compositedata: res.data.content,
							compositedisplay: true
						}
					});
				} else {
					dispatch({
						type: 'exam/update',
						payload: {
							compositedata: null,
							compositedisplay: false
						}
					});
					if (exam.cardMode === true) {
						action.formAct.oneAction(exam.billid);
					} else {
						this.pubSub.publish('initData');
					}
					if (res.data.errorMsg) {
						toast({ color: 'danger', content: res.data.errorMsg });
					} else {
						toast({ color: 'success', content: exam.json['gx6008-000047'] });
					}
				}
			}
		} catch (e) {
			throw e;
		}
	};

	turnOff = () => {
		const { props } = this.comp;
		const { dispatch } = props;
		dispatch({
			type: 'exam/update',
			payload: {
				compositedata: null,
				compositedisplay: false
			}
		});
	};
	// 批量收回
	batchBack = async () => {
		const { props, action } = this.comp;
		const { dispatch, exam, form } = props;

		try {
			let arr = this.billidTool();
			if (arr.length <= 0 && exam.cardMode === false) {
				return;
			}
			let postData = {
				billids: exam.cardMode === true ? exam.billid : arr,
				pk_org: exam.refValue.refpk
			};
			let res = await dispatch({
				type: 'exam/batchBack',
				payload: {
					postData: postData
				}
			});
			if (res.success) {
				// 收回成功
				if (exam.cardMode === true) {
					action.formAct.oneAction(exam.billid);
				} else {
					this.pubSub.publish('initData');
				}
				if (res.data.errorMsg) {
					toast({ color: 'warning', content: res.data.errorMsg });
					return
				}
				toast({ color: 'success', content: exam.json['gx6008-000048'] });
			}
		} catch (e) {}
	};
	// 发送通知
	sendMsgAction = async () => {
		const { props, action } = this.comp;
		const { dispatch, exam, form } = props;

		try {
			let arr = this.billidTool();
			if (arr.length <= 0 && exam.cardMode === false) {
				return;
			}
			let postData = {
				billids: exam.cardMode === true ? exam.billid : arr,
				pk_org: exam.refValue.refpk
			};
			let res = await dispatch({
				type: 'exam/sendMsgAction',
				payload: {
					postData: postData
				}
			});
			if (res.success) {
				// 发送成功！
				toast({ color: 'success', content: exam.json['gx6008-000110'] });
			}
		} catch (e) {}
	};
	// 执行前校验
	batchImplementBefore = async () => {
		const { props, action } = this.comp;
		const { dispatch, exam, form, editTable } = props;
		let effectTime = ''
		if (exam.cardMode) {
			effectTime = form.getFormItemsValue('card', 'regulardate').value;
		} else {
			effectTime = editTable.getCheckedRows('list')[0].data.values.regulardate.value;
			console.log(effectTime)
		}
		dispatch({
			type: 'exam/update',
			payload: {
				effectTime: effectTime//formatDate(new Date()) //生效日期
			}
		});
		try {
			let arr = this.billidTool();

			if (arr.length <= 0 && exam.cardMode === false) {
				return;
			}
			let postData = {
				billids: exam.cardMode === true ? exam.billid : arr,
				pk_org: exam.refValue.refpk
			};
			let res = await dispatch({
				type: 'exam/batchImplementBefore',
				payload: {
					postData: postData
				}
			});
			if (res.success) {
				if (res.data.warning === true) {
					promptBox({
						color: 'warning',
						title: exam.json['gx6008-000111'], //您确定要执行吗
						noCancelBtn: false,
						content: res.data.warningMsg,
						beSureBtnName: exam.json['gx6008-000024'], //确定
						cancelBtnName: exam.json['gx6008-000025'], //取消
						hasCloseBtn: false,
						beSureBtnClick: this.batchBacksBox.bind(this, postData.billid)
					});
				} else {
					this.batchBacksBox(postData.billid);
				}
			}
		} catch (e) {}
	};
	// 执行
	batchBacksBox = async (billid) => {
		const { props, action } = this.comp;
		const { dispatch, exam, form } = props;
		dispatch({
			type: 'exam/update',
			payload: {
				timeModal: true
			}
		});
	};
	// 确认执行

	batchImplement = async () => {
		const { props, action } = this.comp;
		const { dispatch, exam, form } = props;
		try {
			let arr = this.billidTool();

			if (arr.length <= 0 && exam.cardMode === false) {
				return;
			}
			let postData = {
				billids: exam.cardMode === true ? exam.billid : arr,
				pk_org: exam.refValue.refpk,
				effectDate: exam.effectTime
			};
			let res = await dispatch({
				type: 'exam/batchImplement',
				payload: {
					postData: postData
				}
			});
			if (res.success) {
				dispatch({
					type: 'exam/update',
					payload: {
						timeModal: false
					}
				});

				if (exam.cardMode === true) {
					action.formAct.oneAction(exam.billid);
				} else {
					this.pubSub.publish('initData');
				}

				toast({ color: 'success', content: exam.json['gx6008-000112'] });
			}
		} catch (e) {}
	};

	effectTime = (value) => {
		let { props } = this.comp;
		let { dispatch } = props;
		dispatch({
			type: 'exam/update',
			payload: {
				effectTime: value
			}
		});
	};

	viewOpinion = (data, index) => {
		let { props } = this.comp;
		let { dispatch } = props;
		return () => {
			dispatch({
				type: 'exam/update',
				payload: {
					approveDetail: true,
					billid: data.values.pk_hi_regapply.value,
					billtype: data.values.transtype.value ? data.values.transtype.value : data.values.pk_billtype.value
				}
			});
		};
	};
}
